//
//  MainViewController.swift
//  103Photos
//
//  Created by 舒磊明 on 2019/1/31.
//  Copyright © 2019年 舒磊明. All rights reserved.
//

import UIKit
import Photos
import PhotosUI

class MainViewController: UICollectionViewController {
    
    let navTitle = "Photos"
    lazy var backBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: nil)
    lazy var confirmBtn = UIBarButtonItem(title: "完成", style: .plain, target: self, action: nil)
    var layoutFlow: UICollectionViewFlowLayout!
    
    var fetchResult: PHFetchResult<PHAsset>!
    fileprivate let imageMaganer = PHImageManager()
    fileprivate var imageSize: CGSize = CGSize.zero

    private var selectedCells: [IndexPath: UICollectionViewCell] = [:]
    //MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        registCell()
        loadPictures()
    }
}

//MARK: - Ui
extension MainViewController {
    private func setUI () {
        // 设置导航标题
        title = navTitle
        
        // 返回按钮
        navigationItem.leftBarButtonItem = backBtn
        // 确认按钮
        navigationItem.rightBarButtonItem = confirmBtn
        
        // 设置集合单元格
        let margin: CGFloat = 2
        let numberOfLine = 4
        let screenW = UIScreen.main.bounds.width
        
        let layoutWH = (screenW - margin * (CGFloat(numberOfLine) - 1)) / CGFloat(numberOfLine)
        layoutFlow.itemSize = CGSize(width: layoutWH, height: layoutWH)
        layoutFlow.minimumInteritemSpacing = margin
        layoutFlow.minimumLineSpacing = margin
        imageSize = CGSize(width: layoutWH, height: layoutWH)
        
        // 设置背景颜色
        collectionView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    }
    
    private func registCell() {
        collectionView.register(MainCollectionCell.self, forCellWithReuseIdentifier: "Cell")
    }
    
    private func loadPictures() {
        if fetchResult == nil {
            let allPhotoOptions = PHFetchOptions()
            allPhotoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
            fetchResult = PHAsset.fetchAssets(with: allPhotoOptions)
        }
    }
}

//MARK: - Collection datasource
extension MainViewController {
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return fetchResult.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let asset = fetchResult.object(at: indexPath.item)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MainCollectionCell
        
        cell.repredentedAssetIdentifier = asset.localIdentifier
        cell.mediaType = asset.mediaType
        
        imageMaganer.requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFill, options: nil) { (image, _) in
            if cell.repredentedAssetIdentifier == asset.localIdentifier {
                cell.imageView.image = image
            }
        }

        return cell
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) else { return }
        if selectedCells[indexPath] == nil {
            selectedCells[indexPath] = cell
        } else {
            selectedCells.removeValue(forKey: indexPath)
        }
        print(selectedCells)
    }
}

//MARK: - Collection view  cell
class MainCollectionCell: UICollectionViewCell {
    
    lazy var imageView: UIImageView = UIImageView()
    lazy var startView: UIImageView = UIImageView()
    
    var repredentedAssetIdentifier: String!
    var mediaType: PHAssetMediaType! {
        didSet {
            setMedia()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(imageView)
        addSubview(startView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        imageView.frame = self.bounds
        
        let startWH: CGFloat = 30
        let startX = (self.frame.width - startWH) / 2
        let startY = (self.frame.height - startWH) / 2
        startView.frame = CGRect(x: startX, y: startY, width: startWH, height: startWH)
        startView.image = #imageLiteral(resourceName: "bofang")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: - Actions
extension MainCollectionCell {
    private func setMedia() {
        if mediaType == PHAssetMediaType.video {
            startView.isHidden = false
        } else {
            startView.isHidden = true
        }
    }
}
